#!/usr/bin/env python
# -*- coding: UTF-8 -*-

def xml_declare(data,head_declare=False,encoding='UTF-8',version='1.0',root=None) :
    xml = ('<?xml version="%s" encoding="%s"?>' % (version,encoding)) if head_declare else ''
    if root :
        xml += '<%s>' % root
        xml += dict2xml(data)
        xml += '</%s>' % root
    else :
        xml += dict2xml(data)
    return xml

def dict2xml(data,key=None):
    xml = ''
    if isinstance(data,dict) :
        for k,v in data.iteritems() :
            if isinstance(v,(list,tuple)) :
                xml += dict2xml(v,k)
            else :
                xml += '<%s>' % k
                xml += dict2xml(v)
                xml += '</%s>' % k
    elif isinstance(data,(list,tuple)) :
        for v in data :
            xml += '<%s>' % key
            xml += dict2xml(v)
            xml += '</%s>' % key
    elif isinstance(data,(int,long,float)) :
        xml += str(data)
    elif getattr(data,'__dict__',None) :
        xml += dict2xml(vars(data))
    else :
        xml += '<![CDATA[%s]]>' % data
    return xml

if __name__ == '__main__' :
    d = {
        'order':{
            'code':'bn12321321',
            'goods':{
                'good':[
                    {
                        'a':'a1',
                        'b':'b1',
                    },
                    {
                        'a':'a2',
                        'b':'b2',
                    },
                ]
            }
        }
    }
    #print xml_declare(d,root='demo')

    class A(object) :
        def __init__(self) :
            self.attr = 'attribute'
    obj = A()
    print xml_declare(obj,root='demo')
